import React, { FC, ReactElement } from 'react'
import { Layout, Menu, Dropdown } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import headImg from '@/assets/images/logo.svg'
import { useStore } from '@/store'
import { IRoute } from '@/interface/router'
import { Link } from 'react-router-dom'
import Icon from '@/components/Icon'
import setRouter from '@/routes'

import './index.scss'

const { Header } = Layout

type Props = {
  token?: string
}

const AppHeader: FC<Props> = () => {
  const { appStore } = useStore()
  const { menus } = appStore
  const openKey: Array<string> = []
  const openMenu: Array<string> = []

  const getMenuTree = (routers: IRoute[]) => {
    return routers.reduce((pre: ReactElement[], item: IRoute) => {
      if (!item.children) {
        pre.push(
          <Menu.Item key={item.key} icon={<Icon type={item.icon} />}>
            <Link to={item.path}>
              <span>{item.title}</span>
            </Link>
          </Menu.Item>,
        )
      } else {
        !item.hidden && pre.push(
          <SubMenu key={item.key} title={item.title} icon={<Icon type={item.icon} />}>
            {getMenuTree(item.children)}
          </SubMenu>,
        )
      }

      return pre
    }, [])
  }
  const { SubMenu } = Menu
  const asyncRoutes = setRouter(menus)
  const menuTree: ReactElement[] = getMenuTree(asyncRoutes)
  menuTree.unshift(<Menu.Item key="logo"><Link to="/"><img src={headImg} alt="logo" className="logo" /></Link></Menu.Item>)

  const rightMenu = (
    <Menu>
      <Menu.Item key="logout">
        <Link to="/logout">
          退出登录
        </Link>
      </Menu.Item>
    </Menu>
  )
  return (
    <Header className="app-header">
      <Menu theme="dark" mode="horizontal" selectedKeys={openKey} defaultOpenKeys={openMenu}>
        {menuTree}
      </Menu>
      <Dropdown className="right-top-me" overlay={rightMenu}>
        <span className="ant-dropdown-link">
          郭文壮 <DownOutlined />
        </span>
      </Dropdown>
    </Header>
  )
}

export default AppHeader
